/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package componentUI;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * Set max length input for component
 * Ex: txtUsername.setDocument(new LimitCharacterDocument(12));
 * Set max length for input is 12 character
 * 
 * @author HoangHai
 */
public class LimitCharacterDocument extends PlainDocument {

    /** Max character for input into component*/
    private int limit;

    public LimitCharacterDocument(int limit) {
        super();
        this.limit = limit;
    }

    public LimitCharacterDocument(int limit, boolean upper) {
        super();
        this.limit = limit;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null) {
            return;
        }

        if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
        }
    }
}
